package co.bugu.code.analysis.application.service;

import co.bugu.code.analysis.infra.entity.Branch;
import co.bugu.code.analysis.infra.repo.BranchRepo;
import org.apache.commons.collections4.CollectionUtils;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author daocers
 * @date 2025/5/27 17:28
 */
@Service
public class BranchService {

    @Autowired
    BranchRepo branchRepo;
    @Autowired
    GitLabApi gitLabApi;

    /**
     * 根据项目ID和分支名称查询分支信息
     *
     * @param projectId 项目ID
     * @param name      分支名称
     * @return 匹配的分支信息，如果没有找到则返回null
     */
    public Branch findByProjectAndName(Long projectId, String name) {
        Branch query = new Branch();
        query.setProjectId(projectId);
        query.setName(name);
        List<Branch> branchList = branchRepo.findByCondition(query);
        if (CollectionUtils.isNotEmpty(branchList)) {
            return branchList.get(0);
        }
        return null;
    }


    /**
     * 获取增量分支信息
     *
     * @param
     * @return
     * @author alei
     * @date 2025/5/30 15:02
     */
    public void fetchDeltaBranches(Long projectId) {
        try {
            List<org.gitlab4j.api.models.Branch> branches = gitLabApi.getRepositoryApi().getBranches(projectId);
            if (CollectionUtils.isEmpty(branches)) {
                return;
            }

            branches.forEach(item -> {
                Date createdAt = item.getCommit().getCreatedAt();
//               如果createdAt在一个月内， 则入库
                if (createdAt.after(new Date(System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000))) {
                    Branch branch = findByProjectAndName(projectId, item.getName());
                    if (null == branch) {
                        branch = new Branch();
                        BeanUtils.copyProperties(item, branch);
                        branchRepo.insert(branch);
                    } else {
                        BeanUtils.copyProperties(item, branch);
                        branchRepo.updateById(branch);
                    }
                }
            });
        } catch (GitLabApiException e) {
            throw new RuntimeException(e);
        }
    }
}
